from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny
from .models import MemberLevel, MemberPoints
from .serializers import MemberLevelSerializer, MemberPointsSerializer, MemberProfileSerializer
from utils.permissions import IsAdminOrReadOnly
from utils.response import api_response

class MemberLevelViewSet(viewsets.ModelViewSet):
    queryset = MemberLevel.objects.all()
    serializer_class = MemberLevelSerializer
    permission_classes = [AllowAny]
    http_method_names = ['get']

class MemberPointsViewSet(viewsets.ModelViewSet):
    serializer_class = MemberPointsSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        if self.request.user.is_staff:
            return MemberPoints.objects.all()
        return MemberPoints.objects.filter(user=self.request.user)

class MemberProfileViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    @action(detail=False, methods=['get', 'put'])
    def profile(self, request):
        """获取或更新会员个人资料"""
        if request.method == 'GET':
            serializer = MemberProfileSerializer(request.user)
            return api_response(data=serializer.data)
        elif request.method == 'PUT':
            serializer = MemberProfileSerializer(request.user, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return api_response(data=serializer.data)
            return api_response(400, str(serializer.errors)) 